package org.example.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;
import java.util.Optional;

/**
 * 通用字段赋值
 *
 * <p>
 *
 * @author jy
 * @since 2023-11-21 09:41
 */
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {
    
    @Override
    public void insertFill(MetaObject metaObject) {
        Date dateNow = new Date();
        String userId = "admin";
        Long tenantId = 1L;
        String displayName = null;
        this.fillHasGetter(metaObject, "tenantId", tenantId);
        this.fillHasGetter(metaObject, "createId", userId);
        this.fillHasGetter(metaObject, "createBy", Optional.ofNullable(displayName).orElse(StringPool.EMPTY));
        this.fillHasGetter(metaObject, "createTime", dateNow);
        this.fillHasGetter(metaObject, "updateId", userId);
        this.fillHasGetter(metaObject, "updateBy", Optional.ofNullable(displayName).orElse(StringPool.EMPTY));
        this.fillHasGetter(metaObject, "updateTime", dateNow);
    }
    
    @Override
    public void updateFill(MetaObject metaObject) {
        Date dateNow = new Date();
        String userId = "admin";
        String displayName = null;
        this.forceFillHasGetter(metaObject, "updateId", userId);
        this.forceFillHasGetter(metaObject, "updateBy", Optional.ofNullable(displayName).orElse(StringPool.EMPTY));
        this.forceFillHasGetter(metaObject, "updateTime", dateNow);
    }
    
    protected void fillHasGetter(MetaObject metaObject, String fieldName, Object fieldVal) {
        if (metaObject.hasGetter(fieldName)) {
            this.fillStrategy(metaObject, fieldName, fieldVal);
        }
    }
    
    /**
     * 强制更新字段值
     *
     * @param metaObject
     * @param fieldName
     * @param fieldVal
     */
    protected void forceFillHasGetter(MetaObject metaObject, String fieldName, Object fieldVal) {
        if (metaObject.hasGetter(fieldName)) {
            setFieldValByName(fieldName, fieldVal, metaObject);
        }
    }
    
}
